﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SAFTCopyToDB
{
    public partial class FormUploadFileToBD : Form
    {
        public string Messages
        {
            get { return txtMessages.Text; }
            set
            {
                txtMessages.Text += string.Format("{0:yyyy/MM/dd HH:mm:ss}: {1}{2}", DateTime.Now, value, Environment.NewLine);
            }
        }
        public string FileName
        {
            get { return txtFileName.Text; }
            set { txtFileName.Text = value; }
        }
        public string ConnectionString
        {
            get { return txtConnectionString.Text; }
            set { txtConnectionString.Text = value; }
        }

        public bool RecreateBD
        {
            get { return checkDeleteBD.Checked; }
            set { checkDeleteBD.Checked = value; }
        }
        public bool JoinMode
        {
            get { return checkJoinMode.Checked; }
            set { checkJoinMode.Checked = value; }
        }


        public FormUploadFileToBD()
        {
            InitializeComponent();
            ConnectionString = Properties.Settings.Default.ConnectionString;
        }

        EFCodeFirstSAFT context = null;
        BackgroundWorker bw = null;

        private void btOK_Click(object sender, EventArgs e)
        {
            if (File.Exists(txtFileName.Text))
            {
                this.progressBar.Value = 0;

                bw = new BackgroundWorker();
                bw.DoWork += bw_DoWork;
                bw.ProgressChanged += bw_ProgressChanged;
                bw.RunWorkerCompleted += bw_RunWorkerCompleted;
                bw.WorkerReportsProgress = true;
                bw.WorkerSupportsCancellation = true;

                bw.RunWorkerAsync();
            }
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Messages = "Finish";
            this.progressBar.Value = 100;
        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.Messages = e.UserState.ToString();
            this.progressBar.PerformStep();
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                int passo = 1, totalPassos = 7;
                using (context = new EFCodeFirstSAFT(ConnectionString))
                {
                    bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Process started");

                    if (this.RecreateBD)
                    {
                        context.Database.Delete();
                        bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Database Deleted");
                    }

                    if (context.Database.CreateIfNotExists())
                        bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Database Created");

                    SAFTXML.AuditFile auditFile = SAFTXML.SAFTXmlFileHelper.LoadFile(txtFileName.Text);
                    bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "SAFT file loaded");

                    SAFTXML.SAFTXmlFileHelper.MapHeader(auditFile.Header, context);
                    bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Header saved");

                    SAFTXML.SAFTXmlFileHelper.MapSalesInvoices(auditFile.SourceDocuments.SalesInvoices, context, JoinMode);
                    bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Sales Invoices saved");

                    SAFTXML.SAFTXmlFileHelper.MapInvoices(auditFile.SourceDocuments.SalesInvoices, context);
                    bw.ReportProgress(CalculaPercentagem(totalPassos, ref passo), "Invoices loaded");
                }

            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder(ex.Message);

                Exception inner = ex.InnerException;
                while (inner != null)
                {
                    sb.AppendLine(inner.Message);
                    inner = inner.InnerException;
                }

                bw.ReportProgress(0, sb.ToString());
            }
        }

        private int CalculaPercentagem(int totalPassos, ref int passo)
        {
            passo++;
            return (int)((passo / totalPassos) * 100);
        }

        private void btSelectFile_Click(object sender, EventArgs e)
        {
            openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "xml files (*.xml)|*.xml";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                FileName = openFileDialog.FileName;
        }

        private void btFechar_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
